#ifndef UNIFIEDGAMERENDERER_H
#define UNIFIEDGAMERENDERER_H

#include <QObject>
#include <QTimer>
#include <QPixmap>
#include <QSize>
#include <QMutex>
#include "gamestateprocessor.h"
#include "renderthread.h"

enum class GameMode {
    SinglePlayer,
    MultiPlayer,
    BattleRoyale
};

/**
 * @brief 统一游戏渲染器
 * 
 * 解决ModernGameController + SinglePlayerGameWidget双重渲染系统冲突
 * 提供统一的渲染接口和管理
 */
class UnifiedGameRenderer : public QObject
{
    Q_OBJECT

public:
    struct RenderConfig {
        int targetFPS = 60;
        bool enableEffects = true;
        bool enableInterpolation = true;
        bool enablePrediction = false;
        QSize renderSize = QSize(800, 600);
    };

    explicit UnifiedGameRenderer(QObject *parent = nullptr);
    ~UnifiedGameRenderer();

    // === 游戏控制 ===
    void startGame(GameMode mode, const RenderConfig &config);
    void stopGame();
    void pauseGame();
    void resumeGame();

    // === 配置管理 ===
    void setRenderConfig(const RenderConfig &config);
    RenderConfig getRenderConfig() const { return m_config; }

    // === 状态查询 ===
    bool isRunning() const { return m_running; }
    bool isPaused() const { return m_paused; }
    GameMode currentMode() const { return m_currentMode; }
    int currentFPS() const;

    // === 性能监控 ===
    struct PerformanceStats {
        int currentFPS = 0;
        double avgFrameTime = 0.0;
        int processedFrames = 0;
        int droppedFrames = 0;
        qint64 totalRenderTime = 0;
    };
    
    PerformanceStats getPerformanceStats() const;

public slots:
    /**
     * @brief 更新游戏状态
     * @param gameState 来自服务器的游戏状态JSON
     */
    void updateGameState(const QJsonObject &gameState);

    /**
     * @brief 设置渲染尺寸
     * @param size 新的渲染尺寸
     */
    void setRenderSize(const QSize &size);

signals:
    /**
     * @brief 渲染帧就绪信号
     * @param frame 渲染好的游戏帧
     */
    void frameReady(const QPixmap &frame);

    /**
     * @brief 游戏结束信号
     * @param reason 结束原因
     */
    void gameEnded(const QString &reason);

    /**
     * @brief FPS变化信号
     * @param fps 当前FPS
     */
    void fpsChanged(int fps);

    /**
     * @brief 渲染错误信号
     * @param error 错误信息
     */
    void renderingError(const QString &error);

    /**
     * @brief 首帧就绪信号
     * @param duration 首帧处理耗时(ms)
     */
    void firstFrameReady(qint64 duration);

    /**
     * @brief 性能统计信号
     * @param stats 性能统计数据
     */
    void performanceStatsUpdated(const PerformanceStats &stats);

    /**
     * @brief 渲染数据更新信号（用于同步 GameRenderer）
     * @param data 渲染就绪数据
     */
    void renderDataUpdated(const RenderReadyGameData &data);

private slots:
    void onRenderDataReady(const RenderReadyGameData &data);
    void onGameEnded(const QString &reason);
    void onFrameReady(const QPixmap &frame);
    void onPerformanceTimer();

private:
    void initializeComponents();
    void startThreads();
    void stopThreads();
    void setupConnections();
    void updatePerformanceStats();

    // === 核心组件 ===
    GameStateProcessor *m_stateProcessor;
    RenderThread *m_renderThread;

    // === 配置和状态 ===
    GameMode m_currentMode;
    RenderConfig m_config;
    bool m_running;
    bool m_paused;
    bool m_hasServerState;  // 是否已收到服务器状态

    // === 性能监控 ===
    QTimer *m_performanceTimer;
    PerformanceStats m_stats;
    mutable QMutex m_statsMutex;
    qint64 m_lastStatsUpdate;

    // === 线程管理 ===
    bool m_threadsRunning;
    int m_threadFailureCount;
    static const int MAX_THREAD_FAILURES = 3;
};

Q_DECLARE_METATYPE(UnifiedGameRenderer::PerformanceStats)

#endif // UNIFIEDGAMERENDERER_H
